package com.ws.soa.consumer.util;

import com.alibaba.fastjson.JSON;

import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import ch.qos.logback.classic.Level;

/**
 * Date: 2019-02-13
 * Time: 18:33
 * Description: 日志工具类
 *
 * @author qiezi
 */
public class LogUtil {

    /**
     * 超时监控日志
     */
    public final static Logger LONG_TIME = LoggerFactory.getLogger("long_time");

    /**
     * 异常监控日志
     */
    public final static Logger EXCEPTION_HANDLER = LoggerFactory.getLogger("exception_handler");

    /**
     * 业务FACADE日志
     */
    public final static Logger FACADE = LoggerFactory.getLogger("facade");

    /**
     * API监控日志
     */
    public final static Logger CONTROLLER = LoggerFactory.getLogger("controller");

    public static void log(Logger logger, Level level, String message) {
        log(logger, level, message, null);
    }

    public static void log(Logger logger, Level level, String message, Throwable t) {
        if (level == null || StringUtils.isBlank(message)) {
            return;
        }
        int logLevel = level.toInt();
        switch (logLevel) {
            case Level.TRACE_INT:
                logger.trace(message, t);
                break;
            case Level.DEBUG_INT:
                logger.debug(message, t);
                break;
            case Level.INFO_INT:
                logger.info(message, t);
                break;
            case Level.WARN_INT:
                logger.warn(message, t);
                break;
            case Level.ERROR_INT:
                logger.error(message, t);
                break;
            default:
                logger.error(message, t);
                break;
        }
    }

    /**
     * 格式化logger
     *
     * @param title   the title
     * @param message the message
     * @return string string
     */
    public static String formatLog(String title, Object... message) {
        StringBuilder sb = new StringBuilder();
        if (StringUtils.isNotBlank(title)) {
            sb.append("[").append(title).append("]。");
        }
        if (!ArrayUtils.isEmpty(message)) {
            sb.append(JSON.toJSONString(message));
        }
        return sb.toString();
    }
}

